package com.example.springboottools.pic;

import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;
import java.util.regex.Pattern;

public class PicCheck {

    public static void main(String[] args) {
        String path = "C:\\Users\\SH102909\\Downloads\\详情\\";
        File file = new File(path);
        File[] flist = file.listFiles();
        List<Map<String,String>> errorList=new ArrayList<>();
        List<String> allSkuList=new ArrayList<>();
        List<String> errorSkuList=new ArrayList<>();
        checkFileZip(flist, errorList,errorSkuList, allSkuList, 20L);
        System.out.println("");
    }


    private static void checkFileZip(File[] flist, List<Map<String, String>> errorList, List<String> errorSkuList, List<String> allSkuList, Long type) {
        System.out.println("文件夹数据："+ JSON.toJSONString(flist==null?null:flist.length));
        for (File filePicDir:flist) {
            String name = filePicDir.getName();
            String renameOutPath = filePicDir.getAbsolutePath();
            System.out.println("文件夹名称"+name);
            File[] files = filePicDir.listFiles();
            if (null==files||files.length==0){
                Map<String,String> map=new HashMap<>();
                map.put(name,"图片不存在");
                errorList.add(map);
                errorSkuList.add(name);
                continue;
            }
            else {
                //排序集合
                List<Integer> picNameNumList=new ArrayList<>();
                List<String> picNameNumList_1=new ArrayList<>();
                List<String> picNameList=new ArrayList<>();
                Boolean checkName=Boolean.FALSE;
                checkName = checkName || (type == 30L); // 主图修改校验图片数字 by lyx on 2022-05-21

                // 校验图片命名
                for (File file1:files) {
                    if (file1.isDirectory()){
                        Map<String,String> map=new HashMap<>();
                        map.put(name,"文件格式有误");
                        errorList.add(map);
                        errorSkuList.add(name);
                        continue;
                    }

                    String name1 = file1.getName();
                    String[] split = name1.split("\\.");
//                    String[] split = null;
//                    int lastDotIndex = name1.lastIndexOf('.');
//                    if (lastDotIndex != -1) {
//                        String beforeLastDot = name1.substring(0, lastDotIndex);
//                        String afterLastDot = name1.substring(lastDotIndex + 1);
//                         split = new String[]{beforeLastDot, afterLastDot};
//                    }
                    if (null==split||split.length==0){
                        Map<String,String> map=new HashMap<>();
                        map.put(name,"不识别的文件");
                        errorList.add(map);
                        errorSkuList.add(name);
                        continue;
                    }

                    String picName = split[0];
                    String suffixName = split[1];
                    if ((!"jpg".equalsIgnoreCase(suffixName))&&(!"png".equalsIgnoreCase(suffixName))){
                        if ("db".equalsIgnoreCase(suffixName)){
                            file1.delete();
                            continue;
                        }else {
                            Map<String,String> map=new HashMap<>();
                            map.put(name,"请选择jpg\\png文件");
                            errorList.add(map);
                            errorSkuList.add(name);
                            continue;
                        }
                    }

                    //todo 校验是否排序（主图，详图）
                    //不检查图片名，重新排序

                    if (checkName){
                        if (picName.contains("_")){
                            String[] s = picName.split("_");
                            checkPicNameSpilt(errorList, errorSkuList,name,name1 ,picNameNumList, s,picNameList,checkName);
                        }else if (picName.contains("-")){
                            String[] s = picName.split("-");
                            checkPicNameSpilt(errorList, errorSkuList,name, name1,picNameNumList, s,picNameList,checkName);
                        }else {
                            boolean numericFlag = isNumeric(picName);
                            if (numericFlag){
                                picNameNumList.add(Integer.valueOf(name1.split("\\.")[0]));
                                picNameList.add(name1);
                            }else {
                                Map<String, String> map = new HashMap<>();
                                map.put(name, "图片名称错误");
                                errorList.add(map);
                                errorSkuList.add(name);
                                continue;
                            }
                        }
                    }else {
                        picNameList.add(name1);
                    }
                }

                // 主图修改只校验图片命名，不重新排序 by lyx on 2022-05-21
                if(type != 30L){
                    if (!CollectionUtils.isEmpty(picNameNumList)){
                        Collections.sort(picNameNumList, new Comparator<Integer>() {
                            @Override
                            public int compare(Integer o1, Integer o2) {
                                return o1.compareTo(o2);
                            }
                        });
                        //判断图片顺序
                        if (picNameNumList.size()==files.length){
                            if (picNameNumList.get(picNameNumList.size()-1)!=files.length){
                                Map<String, String> map = new HashMap<>();
                                map.put(name, "图片名称排序有误");
                                errorList.add(map);
                                errorSkuList.add(name);
                                continue;
                            }
                        }
                    }
                    if (!checkName){
                        if (!CollectionUtils.isEmpty(picNameList)){

                            Collections.sort(picNameList,new Comparator<String>() {
                                @Override
                                public int compare(String o1, String o2) {
                                    return o1.compareTo(o2);
                                }
                            });
                            System.out.println("排序后图片："+JSON.toJSONString(picNameList));
                            Map<String, String> errorMap=new HashMap<>();
                            for(int i=0;i<picNameList.size();i++){
                                String newName=i+1+".jpg";
                                //renameFile(renameOutPath, picNameList.get(i), newName);
                                renameFileReturnMap(renameOutPath, picNameList.get(i), newName,errorMap);

                            }
                            if (!CollectionUtils.isEmpty(errorMap)){
                                for (Map.Entry<String, String> map:errorMap.entrySet()) {
                                    renameFile(renameOutPath, map.getKey(), map.getValue());
                                }
                            }
                            //检查是否全部转为数字

                        }
/*
                if (!CollectionUtils.isEmpty(picNameList)){

                        Collections.sort(picNameList,new Comparator<String>() {
                            @Override
                            public int compare(String o1, String o2) {
                                int o1length=o1.length();
                                int o2length=o2.length();
                                int legnthdeff=o1length-o2length;
                                if(legnthdeff>0){
                                    return 1;
                                }else if(legnthdeff<0){
                                    return -1;
                                }
                                String o1num=o1.substring(o1.indexOf("-")+1,o1.indexOf("."));
                                String o2num=o2.substring(o2.indexOf("-")+1,o2.indexOf("."));
                                int deff=Integer.parseInt(o1num)-Integer.parseInt(o2num);
                                if(deff>0){
                                    return 1;
                                }else if(deff<0){
                                    return -1;
                                }
                                return 0;
                            }
                        });
                        for(int i=0;i<picNameList.size();i++){
                            String newName=i+1+".jpg";
                            renameFile(renameOutPath, picNameList.get(i), newName);

                        }
                    }
*/
                    }
                    //todo 校验图片像素是否为（800*800）
                }
            }
            //sku带单位
            allSkuList.add(name);
        }
    }
    public static void renameFile(String path, String oldName, String newName){
        if(!oldName.equals(newName)){
            File oldFile = new File(path+"/"+oldName);
            File newFile = new File(path+"/"+newName);
            if(newFile.exists()){
                System.out.println(newName+"已经存在");
            }
            else{
                oldFile.renameTo(newFile);
            }

        }
    }

    public static Map<String,String> renameFileReturnMap(String path, String oldName, String newName,Map<String,String> errorMap){
        if(!oldName.equals(newName)){
            File oldFile = new File(path+"/"+oldName);
            File newFile = new File(path+"/"+newName);
            if(newFile.exists()){
                errorMap.put(oldName,newName);
            }
            else{
                oldFile.renameTo(newFile);
            }

        }
        return errorMap;
    }
    public static boolean isNumeric(String string){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(string).matches();
    }
    private static void checkPicNameSpilt(List<Map<String, String>> errorList, List<String> errorSkuList, String name, String name1, List<Integer> picNameNumList, String[] s, List<String> picNameList, Boolean flag) {
        System.out.println("图片名称数字检查："+JSON.toJSONString(s));
        if (flag){
            if (s.length == 2) {
                if (isNumeric(s[1])) {
                    picNameNumList.add(Integer.valueOf(s[1]));
                    picNameList.add(name1);
                } else {
                    Map<String, String> map = new HashMap<>();
                    map.put(name, "图片名称错误");
                    errorList.add(map);
                    errorSkuList.add(name);
                }
            } else {
                Map<String, String> map = new HashMap<>();
                map.put(name, "图片名称错误");
                errorList.add(map);
                errorSkuList.add(name);
            }
        }
    }
}
